package com.bwie.filter;

import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: Month-03a-lx1
 * @BelongsPackage: com.bwie.filter
 * @Author: asus
 * @CreateTime: 2025-08-29  10:54
 * @Description:
 * @Version: 1.0
 */
@Component
public class LoginFilter implements GlobalFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求路径
        String path = request.getURI().getPath();

        //设置白名单
        if(path.contains("userLogin") || path.contains("upLoadFile")){
            return chain.filter(exchange);
        }

        //验证请求路径中是否携带token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            return response.setComplete();
        }
        //解析token
        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);
        //获取redis中存入的token 进行判断
        String redisToken = redisTemplate.opsForValue().get("token:" + userId);
        if (StringUtils.isEmpty(redisToken)){
            return response.setComplete();
        }
        if (!redisToken.equals(token)){
            return response.setComplete();
        }

        //延长token时间15
        redisTemplate.expire("token:"+userId,15, TimeUnit.MINUTES);

        return chain.filter(exchange);
    }
}
